<?php

/**
 * @category   mediad2
 * @package    Mediad2_Service
 */
class Mediad2_Service_Admin_User extends Mediad2_Service_Abstract
{
	/**
	 * const
	 */
	 
	//General Failure
	const FAILURE                        =  0;

	//Failure due to identity not being found.
	const FAILURE_IDENTITY_NOT_FOUND     = -1;
	
	//Failure due to identity being ambiguous.
	const FAILURE_IDENTITY_AMBIGUOUS     = -2;
	
	//Failure due to invalid credential being supplied.
	const FAILURE_CREDENTIAL_INVALID     = -3;
	
	//Failure due to uncategorized reasons.
	const FAILURE_UNCATEGORIZED          = -4;
	
	//Authentication success and user status is normal
	const SUCCESS_USERSTATUS_NORMAL      =  1;
	
	//Authentication success and user status is pause
	const SUCCESS_USERSTATUS_PAUSE       =  2;
	
	/**
	 * 初始化
	 */
	public function init()
	{
		$this->setMapper('Mediad2_Mapper_User');
		$this->setModel('Mediad2_Model_User');
	}
	
	/**
	 * 通过Email进行登录
	 *
	 * @param string $email
	 * @param string $pwd
	 * @param boolean $isEncrypt
	 * @return Zend_Auth_Result::code|Mediad2_Model_User::STATUS...
	 */
	public function loginByEmail($email, $pwd, $isEncrypt=false)
	{
		return $this->_login('email', $email, $pwd, $isEncrypt);
	}
	
	/**
	 * 登录
	 *
	 * @param string $authFieldName
	 * @param string $authFieldValue
	 * @param string $authPwd
	 * @param boolean $isEncrypt
	 * @return Zend_Auth_Result::code|Mediad2_Model_User::STATUS...
	 */
	private function _login($authFieldName, $authFieldValue, $authPwd, $isEncrypt=false)
	{
		/**
		 * 配置认证参数
		 */
		// get DbAdapter from Registry
		$db = Zend_Registry::get('db1');
	
		// Save a reference to the Singleton instance of Zend_Auth
		$auth = Zend_Auth::getInstance();
	
		// Use 'Mediad' instead of 'Zend_Auth'
		// Use 'identity' instead of 'storage'
		$auth->setStorage(new Zend_Auth_Storage_Session('Mediad2','User'));
	
		// Set up the auth adapter, $authAdapter
		$authAdapter = new Zend_Auth_Adapter_DbTable(
				$db,
				'user',
				$authFieldName,
				'pwd',
				'?'
				// 				'? AND status = 1'	//要求用户状态为1，即正常状态
		);
		
		// 设置密码
		if (!$isEncrypt) $authPwd = md5($authPwd);
	
		// 设置输入的证书的值
		$authAdapter->setIdentity($authFieldValue);
		$authAdapter->setCredential($authPwd);
		try {
			// 验证
			$result = $auth->authenticate($authAdapter);
			// 判断状态
			if ($result->isValid()) {	//认证通过，还需要判断用户状态
				$status = $authAdapter->getResultRowObject()->status;
				switch ($status) {
					case Mediad2_Model_User::STATUS_NORMAL:	//正常状态
					case Mediad2_Model_User::STATUS_SYSTEM:	//系统状态
						$uid = $authAdapter->getResultRowObject()->uid;
						$storage = $auth->getStorage();
						$user = $this->find($uid)->getData();
						$storage->write($user);
						Zend_Registry::set('auth', $auth);
						//返回结果--成功
						return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS,null,self::SUCCESS_USERSTATUS_NORMAL);
			
					case Mediad2_Model_User::STATUS_PAUSE:		//暂停状态
						//返回结果--成功
						return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS,null,self::SUCCESS_USERSTATUS_PAUSE);
			
					default:									//删除或其他状态
						//返回结果--成功
						return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS,null,self::FAILURE);
				}
			} else {
				//认证未通过，返回false
				//返回结果--成功
				return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS,null,$result->getCode());
			}
			
		} catch (Zend_Exception $e) {
			//出错处理
			$this->handleException($e);			
			//返回结果--失败
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE);			
		}

	}
	
	/**
	 * 用户注册，新增一个用户
	 *
	 * @param Mediad2_Model_User
	 * @return Mediad2_Model_Result if success then result_data include uid
	 */
	public function register($model)
	{
		//事务处理
		$db1 = Zend_Registry::get('db1');
		$db1->beginTransaction();
	
		try {
			//保存UserInfo数据
			$mapper = $this->getMapper();
			$uid = $mapper->insert($model->toArray());
			
			$db1->commit(); //提交数据库
			return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS,null,$uid); //返回结果--成功
			
		} catch (Zend_Exception $e) {	
			$db1->rollBack(); //回滚
			$this->handleException($e); //出错处理
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE); //返回结果--失败
		}

	}
	
	/**
	 * 激活用户账号
	 *
	 * @param string $uid
	 * @param string $verifyCode
	 * @return Mediad2_Model_Result
	 */
	public function activate($uid, $verifyCode)
	{
		try {
			$user = $this->find($uid)->getData();
			//判断验证码是否相符
			if (!$verifyCode == $user->getVerifyCode()) {
				return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE, '验证码不符');
			}
			//用户状态改为正常
			$user->setStatus(Mediad2_Model_User::STATUS_NORMAL);
			
			//更新User
			return $this->update($user);
	
		} catch (Zend_Exception $e) {
			//出错处理
			$this->handleException($e);
			//返回结果--失败
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE);
		}
	}
	
	/**
	 * logout
	 *
	 * @return void
	 */
	public function logout()
	{
		Zend_Auth::getInstance()->clearIdentity();
	}
	
	/**
	 * 设置/取消管理员角色
	 * @param array|string $objectId
	 * @param boolean $isCancel
	 */
	public function setadmin($objectId, $isCancel=false)
	{
		try {
			if ($isCancel) {
				$row = array(
					'isadmin' => 0,
				);
			} else {
				$row = array(
					'isadmin' => 1,
				);
			}
			if (!is_array($objectId)) $objectId = explode(',', $objectId);
			$where = "uid in (" . implode(',', $objectId) . ")";
			$mapper = $this->getMapper();
			$mapper->__updateSQL($row, $where);
			
			//返回结果--成功
			return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS);
		
		} catch (Zend_Exception $e) {
			//出错处理
			$this->handleException($e);
			//返回结果--失败
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE);
		}
	}
	
	/**
	 * 允许/取消登录
	 * @param array|string $objectId
	 * @param boolean $isCancel
	 */
	public function allowpass($objectId, $isCancel=false)
	{
		try {
			if ($isCancel) {
				$row = array(
						'status' => Mediad2_Model_User::STATUS_PAUSE,
				);
			} else {
				$row = array(
						'status' => Mediad2_Model_User::STATUS_NORMAL,
				);
			}
			
			if (!is_array($objectId)) $objectId = explode(',', $objectId);
			$where = "uid in (" . implode(',', $objectId) . ")";
			$mapper = $this->getMapper();
			$mapper->__updateSQL($row, $where);
	
			//返回结果--成功
			return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS);
	
		} catch (Zend_Exception $e) {
			//出错处理
			$this->handleException($e);
			//返回结果--失败
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE);
		}
	}
	
	/**
	 * 用户注册（通过昵称）
	 * @param string $nickname
	 * @param string $imei
	 * @return Mediad2_Model_Result
	 */
	public function registerByNickname($nickname,$imei)//change by vincent 20130813
	{
		$fail = Mediad2_Model_Result::CODE_FAILURE;
		$where 	= sprintf("imei = '%s'",$imei);
		
		//验证用户IMEI[begin]
		//判断IMEI是否存在[1]
		$userResult = $this->findBy($where);
		if(!$userResult->getCode())//系统错误返回
			return $this->returnResult($fail,"moblie user error 297");
		
		$moblieUser = $userResult->getData();
		//已IMEI注册的用户,直接返回用户信息[2]
		if($moblieUser->getUid()){
			$uid = $moblieUser->getUid();
			$auth = $this->functions->createAuth($uid, $moblieUser->getQrcode());
			$data = array(
					'auth' 	=> $auth,
					'qrcode'=> $moblieUser->getQrcode(),
			);
			return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS,"registed user!",$data);
		}			
		//没有IMEI的请求做下面的注册处理[3][end]
		
		try {
			$user = new Mediad2_Model_User();
			//构造UserInfo
			$user->setNickname($nickname);							//昵称
			$user->setEmail('');									//用户账户
			$user->setPwd('');										//密码-MD5
			$user->setMobile('');									//电话
			$user->setQq('');										//QQ
			$user->setIsadmin(0);									//是否是管理员
			$user->setStatus($user::STATUS_NORMAL);					//用户状态初始为正常
			$user->setAddtime(time());								//注册日期为当前日
			$user->setRolecode('mobile');							//角色
			$user->setQrcode(strtoupper(md5(uniqid(mt_rand(), true))));//唯一标识码
			$user->setVerifyCode(substr($user->getQrcode(),0,4));	//验证码
			$user->setAvatar('');									//头像
			$user->setSpaceimg('');									//空间背景图片
			$user->setImei($imei);
			
			//注册
			$result = $this->register($user);
			if ($result->getCode() == Mediad2_Model_Result::CODE_SUCCESS) {
				$uid = $result->getData();
				$auth = $this->functions->createAuth($uid, $user->getQrcode());
				$data = array(
						'auth' 	=> $auth,
						'qrcode'=> $user->getQrcode(),
				);
				$result = $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS,null,$data);
			}
			return $result;
		} catch(Zend_Exception $e) {
			$this->handleException($e); //出错处理
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE);	//返回结果--失败
		}
	
	}
	
	/**
	 * 用户登录
	 * @param string $email
	 * @param string $pwd
	 * @return Mediad2_Model_Result
	 */
	public function loginReturnAuth($email, $pwd)
	{
		try {
			$result = $this->loginByEmail($email, $pwd, true);
			if ($result->getCode() == Mediad2_Model_Result::CODE_SUCCESS) {
				$status = $result->getData();
				if ($status == Mediad2_Service_Admin_User::SUCCESS_USERSTATUS_NORMAL) {
					//获取uid
					$registry = Zend_Registry::getInstance();
					$identity =  $registry->auth->getIdentity();
					$uid = $identity->uid;
					$auth = $this->functions->createAuth($uid, $email.$pwd);
					$data = array(
							'auth' 	=> $auth,
							'qrcode'=> $identity->getQrcode(),
					);
					$result = $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS,null,$data);
				} else {
					$result = $this->returnResult(Mediad2_Model_Result::CODE_FAILURE,'user or password is wrong');
				}
			}
			return $result;
	
		} catch(Zend_Exception $e) {
			$this->handleException($e); //出错处理
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE);	//返回结果--失败
		}
	}
	
	/**
	 * binding by email
	 * @param int $uid
	 * @param string $email
	 * @param string $pwd
	 * @return Mediad2_Model_Result
	 */
	public function bindingByEmail($uid, $email, $pwd)
	{
		//var
		$mapper = $this->getMapper();
	
		try {
			//判断email是否已经被绑定
			$where = "email = '$email'";
			$count = $mapper->getCount($where);
			if ($count>0) {
				return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE,'Email已被占用，请重新输入');
			} else {
				$row = array(
						'email' => $email,
						'pwd'	=> $pwd,
				);
				$where = "uid = $uid";
				$mapper->__updateSQL($row, $where);
				return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS,'Email绑定成功');
			}
	
		} catch(Zend_Exception $e) {
			$this->handleException($e); //出错处理
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE);	//返回结果--失败
		}
	}
	
	/**
	 * binding by mobile
	 * @param int $uid
	 * @param string $mobile
	 * @return Mediad2_Model_Result
	 */
	public function bindingByMobile($uid, $mobile)
	{
		//var
		$mapper = $this->getMapper();
	
		try {
			$row = array(
					'mobile' => $mobile,
			);
			$where = "uid = $uid";
			$mapper->__updateSQL($row, $where);
	
			return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS);
		} catch(Zend_Exception $e) {
			$this->handleException($e); //出错处理
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE);	//返回结果--失败
		}
	}
	
	/**
	 * 上传用户头像
	 * @param int $uid
	 * @param string $upload_name
	 * @return Mediad2_Model_Result
	 */
	public function uploadUserimg($uid, $upload_name='Filedata')
	{
		try {
			$sourcetype = Mediad2_Model_Files::SOURCETYPE_PHONE;
			$sourceid 	= $uid;
			
			//上传文件接收和处理
			$serviceFiles = new Mediad2_Service_Admin_Files();
			$result = $serviceFiles->upload($sourcetype, $sourceid, $upload_name);
			
			//处理文件出现失败，则终止处理
			if ($result->getCode() == $result::CODE_FAILURE) {
				return $result;
			}
			
			//处理上传文件正常，则继续
			//获取fid
			$files = $result->getData();
			$fid = $files->getFid();

			//更新用户头像信息
			$row = array(
					'avatar' => $fid,
			);
			$where = "uid = $uid";
			$mapper = $this->getMapper();
			$mapper->__updateSQL($row, $where);
			
			return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS);
			
		} catch (Zend_Exception $e) {
			$this->handleException($e);
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE,'上传用户头像失败，请重试');
		}
	}
	
	/**
	 * 上传用户空间背景图片
	 * @param int $uid
	 * @param string $upload_name
	 * @return Mediad2_Model_Result
	 */
	public function uploadUserSpaceImg($uid, $upload_name='Filedata')
	{
		try {
			$sourcetype = Mediad2_Model_Files::SOURCETYPE_PHONE;
			$sourceid 	= $uid;
	
			//上传文件接收和处理
			$serviceFiles = new Mediad2_Service_Admin_Files();
			$result = $serviceFiles->upload($sourcetype, $sourceid, $upload_name);
	
			//处理文件出现失败，则终止处理
			if ($result->getCode() == $result::CODE_FAILURE) {
				return $result;
			}
	
			//处理上传文件正常，则继续
			//获取fid
			$files = $result->getData();
			$fid = $files->getFid();
	
			//更新用户头像信息
			$row = array(
					'spaceimg' => $fid,
			);
			$where = "uid = $uid";
			$mapper = $this->getMapper();
			$mapper->__updateSQL($row, $where);
	
			return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS);
	
		} catch (Zend_Exception $e) {
			$this->handleException($e);
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE,'上传用户空间背景图片失败，请重试');
		}
	}
	
	/**
	 * 获得用户信息
	 * @param int $uid
	 * @return Mediad2_Model_Result
	 */
	public function getUserInfo($uid)
	{
		try {
			//var 
			$serviceFiles = new Mediad2_Service_Admin_Files();
			
			//查询用户信息
			$result = $this->find($uid);
			if ($result->getCode() == $result::CODE_FAILURE) {
				return $result;
			}
			
			//获取用户信息
			$user = $result->getData();
			
			//获取头像信息
			$avatar_fid = $user->getAvatar();
			$resultFiles = $serviceFiles->find($avatar_fid);
			if ($resultFiles->getCode() == $resultFiles::CODE_FAILURE) {
				return $resultFiles;
			}
			$avatar_files = $resultFiles->getData()->toArray();
			$avatar_files = $serviceFiles->unsetFiles($avatar_files);	//清除数据
			
			//获取空间背景图片
			$spaceimg_fid = $user->getSpaceimg();
			if(isset($spaceimg_fid)){//by vincent 如果没有背景图片,就返回空
				$resultSpaceImg = $serviceFiles->find($spaceimg_fid);
				if ($resultSpaceImg->getCode() == $resultSpaceImg::CODE_FAILURE) {
					return $resultSpaceImg;
				}
				$spaceimg_files = $resultSpaceImg->getData()->toArray();
				$spaceimg_files = $serviceFiles->unsetFiles($spaceimg_files);	//清除数据
			}else{
				$spaceimg_files = new MM_Model_EventFiles();
				$spaceimg_files = $spaceimg_files->toArray();
			}
			
			//封装数据
			$data = array(
					'nickname'	=> $user->getNickname(),
					'email'		=> $user->getEmail(),
					'mobile'	=> $user->getMobile(),
					'qq'		=> $user->getQq(),
					'avator'	=> $avatar_files,
					'spaceimg'  => $spaceimg_files,
					);
		
			return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS,null,$data);
		
		} catch (Zend_Exception $e) {
			$this->handleException($e);
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE,'获取用户信息失败，请重试');
		}
	}
	
	/**
	 * change password
	 * @param string $oldpwd
	 * @param string $newpwd
	 * @param boolean $isEncrypt
	 * @return Mediad2_Model_Result
	 */
	public function changePwd($oldpwd, $newpwd, $isEncrypt=FALSE)
	{
		if (!$isEncrypt) {
			$oldpwdMD5 = md5($oldpwd);
			$newpwdMD5 = md5($newpwd);
		} else {
			$oldpwdMD5 = $oldpwd;
			$newpwdMD5 = $newpwd;
		}
		
		//查找用户
		$result = $this->serviceUser->find($this->uid);
		if ($result->getCode()==Mediad2_Model_Result::CODE_SUCCESS) {
			$model = $result->getData();
			if($oldpwd && $newpwd){//更改密码
				if ($oldpwdMD5 == $model->getPwd()) {
					$model->setPwd($newpwdMD5);
					$result = $this->update($model);
				} else {
					$result = $this->returnResult(Mediad2_Model_Result::CODE_FAILURE,"旧密码有误");
				}
			}
		}
		return $result;
	}
	
	/**
	 * Change Status
	 * @param int $uid
	 * @param int $status
	 * @return Mediad2_Model_Result
	 */
	public function changeStatus($uid, $status)
	{
		try {
			//更新用户状态
			$row = array(
				'status' => $status,
			);
			$where = "uid = $uid";
			$mapper = $this->getMapper();
			$mapper->__updateSQL($row, $where);
			return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS);
		} catch (Zend_Exception $e) {
			$this->handleException($e);
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE,"Can't change user status.");
		}
	}
	
	/**
	 * reset password
	 * @param int $operid  操作员
	 * @param int $objectid 对象id
	 * @return Mediad2_Model_Result
	 */
	public function resetPwd($operid, $objectid)
	{
		try {
			//判断指定operid的操作者是否具备admin权限
			$oper = $this->getMapper()->find($operid)->toArray();
			if ($oper['isadmin'] == Mediad2_Model_User::ISADMIN_NO)
				return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE,"Only administrators have permission."); 

			//设置初始密码为888888
			$pwd = md5('888888');
			//更新用户状态
			$row = array(
					'pwd' => $pwd,
			);
			$where = "uid = $objectid";
			$mapper = $this->getMapper();
			$mapper->__updateSQL($row, $where);
			return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS);
		} catch (Zend_Exception $e) {
			$this->handleException($e);
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE);
		}
	}
	
	/**
	 * verify email 验证邮箱是否已存在
	 * @param string $email 
	 * @return Mediad2_Model_Result
	 */
	public function verifyEmail($email)
	{
		try {
			$where = "email = '$email'";
			$count = $this->getMapper()->getCount($where);
			return $this->returnResult(Mediad2_Model_Result::CODE_SUCCESS,null,$count);
		} catch (Zend_Exception $e) {
			$this->handleException($e);
			return $this->returnResult(Mediad2_Model_Result::CODE_FAILURE);
		}
	}

}